using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.CodeGenerator.Data
{
	public class MethodParameter
	{
		protected string _parameterName;
		protected Method _method;
		protected TableProperty _property;

		public MethodParameter(string name, Method method, TableProperty property)
		{
			_parameterName = name;
			_method = method;
			_property = property;
		}

		public string ParameterName
		{
			get { return _parameterName; }
			set { _parameterName = value; }
		}

		public Method Method
		{
			get { return _method; }
		}

		public TableProperty Property
		{
			get { return _property; }
			set { _property = value; }
		}

		public void SaveXml(XmlDocument doc, XmlElement parent)
		{
			XmlElement el = CreateXmlElement(doc);
			parent.AppendChild(el);
		}

		public XmlElement CreateXmlElement(XmlDocument doc)
		{
            
            //TODOS GPC
			XmlElement el = doc.CreateElement("MethodParameter");
            try
            {

                el.Attributes.Append(doc.CreateAttribute("ParameterName")).Value = _parameterName;
                el.Attributes.Append(doc.CreateAttribute("Property")).Value = _property.ColumnName;
            }
            catch(Exception exp)
            {

                string logstr = exp.ToString();
                if (_parameterName != null)
                    logstr += _parameterName;
                DataHelper.LogDataError(logstr);

            }

			return el;
		}

		public void LoadXml(XmlElement xmlParameter)
		{
			_parameterName = xmlParameter.GetAttribute("ParameterName");

			string propName = xmlParameter.GetAttribute("Property");

			foreach ( TableProperty prop in _method.Table.Properties )
			{
				if ( prop.Type == TablePropertyType.PrimaryKey )
				{
					PrimaryKeyTableProperty pk = prop as PrimaryKeyTableProperty;

					if ( propName == "" )
					{
						_property = pk;
						return;
					}

					foreach ( TableProperty pkprop in pk.Properties )
					{
						if ( pkprop.ColumnName == propName )
						{
							_property = pkprop;
							return;
						}
					}
				}
				else
				{
					if ( prop.ColumnName == propName )
					{
						_property = prop;
						return;
					}
				}
			}
		}

		public override string ToString()
		{
			return _parameterName;
		}
	}
}
